package com.ruoyi.system.service.impl;

import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SysSupplierMapper;
import com.ruoyi.system.domain.SysSupplier;
import com.ruoyi.system.service.ISysSupplierService;
import com.ruoyi.common.core.text.Convert;

/**
 * 供应商信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2020-12-13
 */
@Service
public class SysSupplierServiceImpl implements ISysSupplierService 
{
    private static final Logger log = LoggerFactory.getLogger(SysSupplierServiceImpl.class);

    @Autowired
    private SysSupplierMapper sysSupplierMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询供应商信息
     * 
     * @param supplierId 供应商信息ID
     * @return 供应商信息
     */
    @Override
    public SysSupplier selectSysSupplierById(Long supplierId)
    {
        return sysSupplierMapper.selectSysSupplierById(supplierId);
    }

    /**
     * 查询供应商信息列表
     * 
     * @param sysSupplier 供应商信息
     * @return 供应商信息
     */
    @Override
    public List<SysSupplier> selectSysSupplierList(SysSupplier sysSupplier)
    {
        return sysSupplierMapper.selectSysSupplierList(sysSupplier);
    }

    /**
     * 新增供应商信息
     * 
     * @param sysSupplier 供应商信息
     * @return 结果
     */
    @Override
    public int insertSysSupplier(SysSupplier sysSupplier)
    {
        sysSupplier.setCreateTime(DateUtils.getNowDate());
        sysSupplier.setState("1");
        int rowId=sysSupplierMapper.insertSysSupplier(sysSupplier);
        SysUser sysUser=new SysUser();
        sysUser.setLoginName(sysSupplier.getAccount());
        sysUser.setUserName(sysSupplier.getSupplierName());
        sysUser.setPassword(sysSupplier.getPassword());
        sysUser.setSalt(sysSupplier.getSalt());
        sysUser.setPhonenumber(sysSupplier.getTelephone());
        //11 为供应商 10为采购商
        sysUser.setUserType("11");
        sysUser.setCompanyId(sysSupplier.getSupplierId());
        return sysUserMapper.insertUser(sysUser);
    }

    /**
     * 修改供应商信息
     * 
     * @param sysSupplier 供应商信息
     * @return 结果
     */
    @Override
    public int updateSysSupplier(SysSupplier sysSupplier)
    {
        sysSupplier.setUpdateTime(DateUtils.getNowDate());
        return sysSupplierMapper.updateSysSupplier(sysSupplier);
    }

    /**
     * 删除供应商信息对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteSysSupplierByIds(String ids)
    {
        return sysSupplierMapper.deleteSysSupplierByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除供应商信息信息
     * 
     * @param supplierId 供应商信息ID
     * @return 结果
     */
    @Override
    public int deleteSysSupplierById(Long supplierId)
    {
        return sysSupplierMapper.deleteSysSupplierById(supplierId);
    }

    @Override
    public int resetUserPwd(SysSupplier sysSupplier) {
        return sysSupplierMapper.updateSysSupplier(sysSupplier);
    }

    /**
     * 导入供应商单位
     * @param userList 供应商单位列表
     * @param updateSupport 是否更新现有数据
     * @param operName 操作者名称
     * @return
     */
    public String importUser(List<SysSupplier> userList, boolean updateSupport, String operName){
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new BusinessException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        String password = configService.selectConfigByKey("sys.supplier.initPassword");
        for (SysSupplier user : userList)
        {
            try
            {
                // 验证供应商表中是否存在这个用户
                SysSupplier su=sysSupplierMapper.selectSysSupplierByAccount(user.getAccount());
                if(StringUtils.isNull(su)){
                    user.setSalt(ShiroUtils.randomSalt());
                    user.setPassword(new Md5Hash(user.getAccount() +  user.getPassword() + user.getSalt()).toHex());
                    user.setCreateBy(ShiroUtils.getLoginName());
                    sysSupplierMapper.insertSysSupplier(user);

                }else{
                    user.setSupplierId(su.getSupplierId());
                    sysSupplierMapper.updateSysSupplier(user);
                }


                // 验证系统用户表是否存在这个用户
                SysUser u = userMapper.selectUserByLoginName(user.getAccount());
                SysUser newUser=new SysUser();
                if (StringUtils.isNull(u))
                {

                    newUser.setSalt(user.getSalt());
                    newUser.setPassword(user.getPassword());
                    newUser.setCreateBy(operName);
                    newUser.setPhonenumber(user.getMoble());
                    newUser.setLoginName(user.getAccount());
                    newUser.setUserName(user.getSupplierName());
                    newUser.setUserType("11");//11表示供应商
                    newUser.setCompanyId(user.getSupplierId());
                    userMapper.insertUser(newUser);
                    Long[] roleIds=new Long[]{3L};
                    userService.insertUserAuth(newUser.getUserId(),roleIds);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getAccount() + " 导入成功");
                }
                else if (updateSupport)
                {
                    u.setSalt(user.getSalt());
                    u.setPassword(user.getPassword());
                    u.setCreateBy(operName);
                    u.setLoginName(user.getAccount());
                    u.setUserName(user.getSupplierName());
                    u.setPhonenumber(user.getMoble());
                    u.setUserType("11");//11表示供应商
                    u.setCompanyId(user.getSupplierId());
                    userMapper.updateUser(u);
                    Long[] roleIds=new Long[]{3L};
                    userService.insertUserAuth(u.getUserId(),roleIds);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getAccount() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getAccount() + " 已存在");
                }



            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getAccount() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
